package com.rd.student.ruanjian.class4.lichunquan.Text03;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

public class Test02 {
    public static void main(String[] args) throws InterruptedException {
        Thread_Test thread_test = new Thread_Test();
        //创建10个线程-----------------------------
        /*Thread t1 = new Thread(thread_test);
        Thread t2 = new Thread(thread_test);
        Thread t3 = new Thread(thread_test);
        Thread t4 = new Thread(thread_test);
        Thread t5 = new Thread(thread_test);
        Thread t6 = new Thread(thread_test);
        Thread t7 = new Thread(thread_test);
        Thread t8 = new Thread(thread_test);
        Thread t9 = new Thread(thread_test);
        Thread t10 = new Thread(thread_test);
        t1 .start();
        t2 .start();
        t3 .start();
        t4 .start();
        t5 .start();
        t6 .start();
        t7 .start();
        t8 .start();
        t9 .start();
        t10.start();
        thread_test.print01();*/
        //一个线程循环10次
       /* for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(thread_test);
            thread.start();
            thread.join();
        }
        thread_test.print02();*/
        //Callable接口
        int sum = 0;
        Thread_Test01 thread_test01 = new Thread_Test01();
        FutureTask<Integer> futureTask = new FutureTask(thread_test01);
        for (int i = 0; i < 10; i++) {
            try {
                sum += futureTask.get();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println(sum);
    }
}

class Thread_Test implements Runnable{
    int Number = 0;
    int sum = 0;
    @Override
    public void run(){
        synchronized (this){
            for (int i = 0; i < 10; i++) {
                Number+=1;
                System.out.println(Thread.currentThread().getName()
                        +" "+Number);
            }
            sum+=Number;
        }
    }
    public void print01(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("sum = " + sum);
    }
    public void print02(){
        System.out.println("sum = " + sum);
    }
}
class Thread_Test01 implements Callable<Integer>{
    volatile int num = 0;
    @Override
    public Integer call() throws Exception {
        for (int i = 0; i < 10; i++) {
            num+=1;
            System.out.println(Thread.currentThread().getName()+" "+num);
        }
        return num;
    }
}